package web;

import beans.LoginStatus;
import beans.User;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import service.UserService;
import Utils.JSONUtils;

import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(value = "/user/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String autoLogin = request.getParameter("autoLogin");
        User user = new User(username, password);
        UserService userService = new UserService();
        User existUser = userService.login(user);
        if (existUser != null) {
            request.getSession().setAttribute("existUser",existUser);
            if (autoLogin != null && autoLogin.equals("on")) {
                Cookie cookie = new Cookie("autoLogin", URLEncoder.encode(JSONUtil.toJsonStr(existUser),"UTF-8"));
                cookie.setMaxAge(7*24*60*60);
                response.addCookie(cookie);
            }
            response.getWriter().write(JSONUtils.result(LoginStatus.LOGIN_SUCCESS, existUser));
        }else {
            response.getWriter().write(JSONUtils.result(LoginStatus.LOGIN_FAIL ,user));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
